package com.museyu.config;

import com.museyu.controller.GameController;
import com.museyu.service.GameService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Component
public class WebSocketEventListener {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Autowired
    private GameController gameController;

    @Autowired
    private GameService gameService;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        String username = headers.getUser() != null ? headers.getUser().getName() : "unknown";
        logger.info("收到新的WebSocket连接: sessionId={}, username={}", sessionId, username);

        // 从请求头中获取玩家ID
        String playerId = headers.getFirstNativeHeader("playerId");
        if (playerId != null) {
            gameService.setPlayerSessionId(playerId, sessionId);
            logger.info("设置玩家会话映射: playerId={}, sessionId={}", playerId, sessionId);
        } else {
            logger.warn("未找到玩家ID，无法设置会话映射");
        }
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        String username = headers.getUser() != null ? headers.getUser().getName() : "unknown";
        logger.info("用户断开连接: sessionId={}, username={}", sessionId, username);
        
        gameService.removePlayerSession(sessionId);
        gameController.playerDisconnected();
    }
} 